import Handlebars from 'handlebars';
import fs from 'node:fs';
import path from 'node:path';
import { pascalCase, camelCase, snakeCase } from 'change-case';

Handlebars.registerHelper('pascal', (s: string) => pascalCase(s));
Handlebars.registerHelper('camel', (s: string) => camelCase(s));
Handlebars.registerHelper('snake', (s: string) => snakeCase(s));
Handlebars.registerHelper('eq', (a: any, b: any) => a === b);


export function renderTemplate(tplName: string, data: any) {
  const tplPath = path.resolve(process.cwd(), 'node_modules', 'nestc', 'templates', tplName);
  const localTplPath = path.resolve(process.cwd(), 'templates', tplName);
  const __dirname = path.dirname(new URL(import.meta.url).pathname);
  // 在 Windows 上修复路径问题
  const normalizedDirname = process.platform === 'win32' && __dirname.startsWith('/') 
    ? __dirname.substring(1) 
    : __dirname;
  const finalPath = fs.existsSync(localTplPath) ? localTplPath : (fs.existsSync(tplPath) ? tplPath : path.resolve(normalizedDirname, '../../templates', tplName));
  const content = fs.readFileSync(finalPath, 'utf-8');
  const tpl = Handlebars.compile(content);
  return tpl(data);
}